package com.imooc.miaosha.activemq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Service;

import com.imooc.miaosha.domain.MiaoshaOrder;
import com.imooc.miaosha.domain.MiaoshaUser;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.MiaoshaService;
import com.imooc.miaosha.service.OrderService;
import com.imooc.miaosha.vo.GoodsVo;

@Service
public class MQReceiver {

		private static Logger log = LoggerFactory.getLogger(MQReceiver.class);
		
		@Autowired
		RedisService redisService;
		
		@Autowired
		GoodsService goodsService;
		
		@Autowired
		OrderService orderService;
		
		@Autowired
		MiaoshaService miaoshaService;
//
        @JmsListener(destination = MQConfig.MIAOSHA_QUEUE,containerFactory = "jmsListenerContainerQueue")
		public void receive(String message) {
			log.info("receive message:"+message);
			MiaoshaMessage mm  = RedisService.stringToBean(message, MiaoshaMessage.class);
			MiaoshaUser user = mm.getUser();
			long goodsId = mm.getGoodsId();

			GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
	    	int stock = goods.getStockCount();
			log.info("stock"+stock);
	    	if(stock <= 0) {
	    		return;
	    	}
	    	//判断是否已经秒杀到了
	    	MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
			log.info("order"+order);
	    	if(order != null) {
	    		return;
	    	}
	    	//减库存 下订单 写入秒杀订单
	    	miaoshaService.miaosha(user, goods);
		}

	   @JmsListener(destination = MQConfig.QUEUE,containerFactory = "jmsListenerContainerQueue")
	   //@SendTo("out.queue") 双向消息 反向 一下  回执 需要在发送端 监听这个out。queue
		public String receiveQueue(String message) {
			log.info("receive message:"+message);
			return  "cousotm result";
		}

	    @JmsListener(destination = MQConfig.TOPIC_QUEUE1,containerFactory = "jmsListenerContainerTopic")
		public void receiveTopic1(String message) {
			log.info(" topic  queue1 message:"+message);
		}


}
